console.log("content.js run", window.location.href)
//监听路由变化
function hashChangeFire(){
    alert("1231561")
}

//url变化监听器
if( ('onhashchange' in window) && ((typeof document.documentMode==='undefined') || document.documentMode==8)) {
    // 浏览器支持onhashchange事件
    window.onhashchange = hashChangeFire;  // TODO，对应新的hash执行的操作函数
} else {
    // 不支持则用定时器检测的办法
    setInterval(function() {
        // 检测hash值或其中某一段是否更改的函数， 在低版本的iE浏览器中通过window.location.hash取出的指和其它的浏览器不同，要注意
        var ischanged = isHashChanged();
        if(ischanged) {
            hashChangeFire();  // TODO，对应新的hash执行的操作函数
        }
    }, 150);
}

//用户登录
var ws;
var nickName;
var video;

if ("WebSocket" in window){
    if(ws == null){
         console.log("新建 WebSocket!");
         ws = new WebSocket("wss://budeliao.info/wss/connect");
        //  ws = new WebSocket("ws://127.0.0.1:9999/connect");
        //  ws = new WebSocket("wss://192.168.206.1:4433/wss/connect");
    }                
    ws.onopen = async function(){
        //构造登录结构体
        nickName = await getItem('nickName');
        console.log("nickName: ", nickName)        
        var url = window.location.href
        video = url.slice(url.indexOf("video/") + 6, url.indexOf("video/") + 18)
        console.log("video: ", video)
        var login = {
            name: nickName,
            video: video,
            type: 'login',
            content: ''
        }
        ws.send(JSON.stringify(login));
        console.log("登录中...");
        //重置心跳机制
        heart.start();
    };
     
    ws.onmessage = function (evt){ 
       var received_msg = evt.data;
       if (received_msg == "pong"){
            console.log("心跳正常");
       }else{
            console.log("数据已接收: ", received_msg);
            chrome.runtime.sendMessage({
                info: received_msg
            }, res => {})
       }
        //重置心跳机制
        heart.start();
    };
     
    ws.onclose = function(msg){
        console.log("连接已关闭: ", msg); 
    };
 }else {
    // 浏览器不支持 WebSocket
    console.log("您的浏览器不支持 WebSocket!");
 }


let heart = {
    timeOut:5000,
    timeObj: null,
    serverTimeObj: null,
    start:function(){
        let self = this;
        //清除延时器
        this.timeObj && clearTimeout(this.timeObj);
        this.serverTimeObj && clearTimeout(this.serverTimeObj);
        var msg = {
            name: nickName,
            video: video,
            type: 'heartbeat',
            content: ''
        }
        this.timeObj = setTimeout(function(){
            ws.send(JSON.stringify(msg));//发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
        },this.timeOut)
    }
}



chrome.runtime.onConnect.addListener(function (port) {//建立监听
    console.log("content 收到监听信号 port: ", port)

    //查询url
    if(port.name == "queryUrl"){
        port.onMessage.addListener(function (msg) {//监听消息
            console.log("[port] queryUrl msg: ", msg)
            port.postMessage({url: window.location.href});//向扩展同返回消息，
        });
    }
    
    
    //查询url
    if(port.name == "getHistory"){
        port.onMessage.addListener(function (msg) {//监听消息
            console.log("[port] getHistory msg: ", msg)
            //获取历史记录
            var sendMessage = {
                name: nickName,
                video: video,
                type: "history",
                content: ""
            }
            ws.send(JSON.stringify(sendMessage));
        });
    }

    //更改昵称
    if(port.name == "changeNickName"){
        port.onMessage.addListener(function (msg) {//监听消息
            console.log("[port] changeNickName msg: ", msg)
            
            localStorage.setItem("nickName", msg)
            //获取历史记录
            var sendMessage = {
                name: nickName,
                video: video,
                type: "changeName",
                content: msg
            }
            ws.send(JSON.stringify(sendMessage));
        });
    }

    //发送消息
    if(port.name == "sendMsg"){
        port.onMessage.addListener(function (msg) {//监听消息
            console.log("[port] sendMsg msg: ", msg)
            var sendMessage = {
                name: nickName,
                video: video,
                type: "message",
                content: msg
            }
            ws.send(JSON.stringify(sendMessage));
        });
    }

    //setData
    if(port.name == "setData"){
        port.onMessage.addListener(function (msg) {//监听消息
            console.log("[port] setData msg: ", msg)
            if(msg.key.length == 0 || msg.value.length == 0){
                port.postMessage({code: 1, msg: 'key 或 value 不能为空！'});
                return
            }
            localStorage.setItem(msg.key, msg.value)
            port.postMessage({code: 0});//向扩展同返回消息，
        });
    }

    //getData
    if(port.name == "getData"){
        port.onMessage.addListener(function (msg) {//监听消息
            console.log("[port] getData msg: ", msg)
            if(msg.key.length == 0){
                port.postMessage({code: 1, msg: 'key不能为空！'});
                return
            }
            let value = localStorage.getItem(msg.key)
            port.postMessage({code:0, value: value});
        });
    }

    if(port.name == "ma"){//判断通道名称
        port.onMessage.addListener(function (msg) {//监听消息
            console.log("content 监听内容 msg: ", msg)
            if(msg.jia== "aaaaaaa"){//如果扩展发送的消息为{jia: "aaaaaaa"}那么改变字体颜色
                console.log("接收到 jia aaaaaaaa")
                port.postMessage({jia: "yuuuuu"});//向扩展同返回消息，
            };
        });
    }

});

async function getItem(key){
    return new Promise((resolve, reject)=>{        
        chrome.storage.local.get([key], function(result) {
            console.log('key is ' , result);
            resolve(result[key])
          });
    })
}
